package com.mvp.lt.airlineview.wayline;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.mvp.lt.airlineview.R;
import com.mvp.lt.airlineview.location.MapMarkerTypeConstant;
import com.mvp.lt.airlineview.map.MapCreateManager;
import com.mvp.lt.airlineview.sendtion.xrichtextdemo.ui.NewActivity;
import com.mvp.lt.airlineview.sendtion.xrichtextdemo.util.ImageUtils;
import com.mvp.lt.airlineview.sendtion.xrichtextdemo.util.MyGlideEngine;
import com.mvp.lt.airlineview.sendtion.xrichtextdemo.util.SDCardUtil;
import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.MapShadowManager;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.text.DecimalFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 作者：uiho_mac
 * 时间：2018/6/7
 * 描述：显示地图
 * 版本：1.
 * 航带
 * 修订历史：
 *
 * @author dan
 */
public class WayLineActivity extends AppCompatActivity implements View.OnClickListener {
    @BindView(R.id.clear_bt)
    Button clearBt;
    @BindView(R.id.check_2)
    Button check2;
    @BindView(R.id.check_3)
    Button check3;

    @BindView(R.id.leftExpansionValue)
    TextView tvLeftExpansionValue;

    @BindView(R.id.left_expansion_seekbar)
    SeekBar leftExpansionSeekBar;

    @BindView(R.id.rightExpansionValue)
    TextView tvRightExpansionValue;

    @BindView(R.id.right_expansion_seekbar)
    SeekBar rightExpansionSeekBar;

    private MapView mapView;
    private AMap aMap;
    private CheckBox mStyleCheckbox;
    public RelativeLayout mLll_layout;
    private int height = 120;
    private int fov = 85;
    public MapShadowManager mMapShadowManager;
    public BandWayLineUtil mStripLineWaypointManager;
    private int mLeftExpansionValue = 20;
    private int mRightExpansionValue = 20;
    private SeekBar mFlyHeightValueSeekBar;
    private SeekBar diskOverlapRatio;
    private TextView flyHeightValue;
    private TextView diskOverlapRatioValue;
    private TextView mTvFlyLength;
    private TextView mTvFlyTime;
    private TextView mTvFlyPoints;
    private TextView mTvFlyPictures;
    private TextView mTvFlyRegionArea;
    private DecimalFormat mDecimalFormat;
    private TextView mCourseOverlapRatioValue;
    private SeekBar mCourseOverlapRatio;
    private Button mCheckPicture;
    private Button mCheckMap;
    private boolean isMapType =false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_way_line_map);
        ButterKnife.bind(this);
        mFlyHeightValueSeekBar = findViewById(R.id.flyHeightValueSeekBar);
        diskOverlapRatio = findViewById(R.id.diskOverlapRatio);
        flyHeightValue = findViewById(R.id.flyHeightValue);
        diskOverlapRatioValue = findViewById(R.id.diskOverlapRatioValue);
        mCourseOverlapRatioValue = findViewById(R.id.courseOverlapRatioValue);
        mCourseOverlapRatio = findViewById(R.id.courseOverlapRatio);
        mLll_layout = findViewById(R.id.lll_layout);
        mapView = (MapView) findViewById(R.id.map);
        mCheckPicture = findViewById(R.id.check_picture);
        mCheckMap = findViewById(R.id.check_map);
        //数据
        mTvFlyLength = findViewById(R.id.tv_fly_length);
        mTvFlyTime = findViewById(R.id.tv_fly_time);
        mTvFlyPoints = findViewById(R.id.tv_fly_points);
        mTvFlyPictures = findViewById(R.id.tv_fly_pictures);
        mTvFlyRegionArea = findViewById(R.id.tv_fly_region_area);

        MapCreateManager.getMapManager().setMapView(this,mapView).buildMap(savedInstanceState);
        mStripLineWaypointManager = new BandWayLineUtil(MapCreateManager.getMapManager().getaMap());
        mCheckMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMapType) {
                    isMapType =false;
                    MapCreateManager.getMapManager().getaMap().setMapType(AMap.MAP_TYPE_SATELLITE);
                } else {
                    isMapType =true;
                    MapCreateManager.getMapManager().getaMap().setMapType(AMap.MAP_TYPE_NORMAL);
                }
            }
        });
        mCheckPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callGallery();
            }
        });
        mStripLineWaypointManager.setStripLineChangeListener(new BandWayLineUtil.StripLineChangeListener() {
            @Override
            public void OnStripLineChange() {
                updateBottomData();
            }
        });
        MapCreateManager.getMapManager().setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                LogUtil.e("Marker", "======onMapClick=====" + "" + latLng.latitude + "================" + latLng.longitude);
                // 113.02743681652198=====28.166934427802392
                // 113.02743681652198=====28.166934427802392
                mStripLineWaypointManager.addLatLngAddDrawWayLine(latLng);
            }
        });

        MapCreateManager.getMapManager().setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                LogUtil.e("数据", "=======点击=======");
                if (marker.getObject() != null) {
                    try {
                        //marker点的类型 常量类 MapMarkerTypeConstant
                        int type = (int) marker.getObject();
                        if (type == MapMarkerTypeConstant.MARKER_TYPE_FLIGHT_BELT_ADD) {
                            mStripLineWaypointManager.onMarkerClick(marker);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                return false;
            }
        });
        MapCreateManager.getMapManager().setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                LogUtil.e("Marker", "开始拖动" + "");
                //航点拖拽
                //带加号的航点拖拽
                mStripLineWaypointManager.onMarkerDragStart(marker);

            }

            @Override
            public void onMarkerDrag(Marker marker) {
                //航点拖拽
                //带加号的航点拖拽
                mStripLineWaypointManager.onMarkerDrag(marker);
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                LogUtil.e("Marker", "结束拖动" + "");
                mStripLineWaypointManager.onMarkerDragEnd(marker);
            }
        });

        initView();
    }


    private void initView() {

        check2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mStripLineWaypointManager.revokeCenterLatLng();
            }
        });
        diskOverlapRatio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    if (progress >= 10 && progress <= 90) {
                        diskOverlapRatioValue.setText("旁向重叠率" + progress);
                        mStripLineWaypointManager.setDiskOverlapRatio(progress);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mCourseOverlapRatio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    if (progress >= 10 && progress <= 90) {
                        mCourseOverlapRatioValue.setText("航向重叠率" + progress);
                        mStripLineWaypointManager.setCourseOverlapRatio(progress);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mFlyHeightValueSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    if (progress >= 25) {
                        flyHeightValue.setText("飞行高度" + progress);
                        mStripLineWaypointManager.setFlyHeight(progress);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        clearBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mStripLineWaypointManager.clearMap();
            }
        });
        leftExpansionSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && progress >= 10) {
                    mLeftExpansionValue = progress;
                    tvLeftExpansionValue.setText("左扩张 " + mLeftExpansionValue);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                mStripLineWaypointManager.setLeftExpansion(mLeftExpansionValue);

            }
        });
        rightExpansionSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && progress >= 10) {
                    mRightExpansionValue = progress;
                    tvRightExpansionValue.setText("右扩张 " + mRightExpansionValue);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mStripLineWaypointManager.setRightExpansion(mRightExpansionValue);
            }
        });
    }


    public void updateBottomData() {
        double length = mStripLineWaypointManager.getLineLength();
        mTvFlyLength.setText(length + "m");
        String flyTime = mStripLineWaypointManager.getWayPointFlyTime(length, 6);
        mTvFlyTime.setText(flyTime);
        int numberPoints = mStripLineWaypointManager.getLineNumbers();
        mTvFlyPoints.setText(numberPoints + "");
        int pictures = mStripLineWaypointManager.getWayPointPictures(length, 6);
        mTvFlyPictures.setText(pictures + "");
        double mAre = mStripLineWaypointManager.getStripRegionArea();
        if (mDecimalFormat == null) {
            mDecimalFormat = new DecimalFormat("###0.0");
        }
        mTvFlyRegionArea.setText(mDecimalFormat.format(mAre) + "m²");
    }

    private static final int REQUEST_CODE_CHOOSE = 23;//定义请求码常量

    /**
     * 调用图库选择
     */
    private void callGallery() {
//        //调用系统图库
//        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");// 相片类型
//        startActivityForResult(intent, 1);

        Matisse.from(this)
                .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF))//照片视频全部显示MimeType.allOf()
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(3)//最大选择数量为9
                //.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))//图片显示表格的大小
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)//图像选择和预览活动所需的方向
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Zhihu)//主题  暗色主题 R.style.Matisse_Dracula
                .imageEngine(new MyGlideEngine())//图片加载方式，Glide4需要自定义实现
                .capture(true) //是否提供拍照功能，兼容7.0系统需要下面的配置
                //参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .captureStrategy(new CaptureStrategy(true, "com.mvp.lt.airlineview.sendtion.matisse.fileprovider"))//存储到哪里
                .forResult(REQUEST_CODE_CHOOSE);//请求码
    }

    //113.042554,28.161107
    //113.042961,28.161016
    private LatLng mLatLng = new LatLng(28.161107, 113.042554);
    private LatLng mLatLng1 = new LatLng(28.161016, 113.042961);

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                } else if (requestCode == REQUEST_CODE_CHOOSE) {
                    //异步方式插入图片
                    List<Uri> mSelected = Matisse.obtainResult(data);
                    // 可以同时插入多张图片
                    for (int i = 0; i < mSelected.size(); i++) {
                        Uri imageUri =mSelected.get(i);
                        String imagePath = SDCardUtil.getFilePathFromUri(WayLineActivity.this, imageUri);
                        LogUtil.e("选择", "###path=" + imagePath);
                        if (i ==0){
                            MapCreateManager.getMapManager().addOverlayToMap(imagePath, mLatLng);
                        }else {
                            MapCreateManager.getMapManager().addOverlayToMap(imagePath, mLatLng1);

                        }
                    }

                }
            }
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        MapCreateManager.getMapManager().onDestroy();
        mStripLineWaypointManager.clearMap();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.basicmap:
                // 矢量地图模式
                aMap.setMapType(AMap.MAP_TYPE_NORMAL);
                break;
            case R.id.rsmap:
                // 卫星地图模式
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.nightmap:
                //夜景地图模式
                aMap.setMapType(AMap.MAP_TYPE_NIGHT);
                break;
            case R.id.navimap:
                //导航地图模式
                aMap.setMapType(AMap.MAP_TYPE_NAVI);
                break;
            default:
                break;
        }
        mStyleCheckbox.setChecked(false);
    }


}
